package com.example.administrator.yanfoxconn.activity;

import android.app.AlertDialog;
import android.content.DialogInterface;
import android.content.Intent;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.graphics.Rect;
import android.os.Build;
import android.os.Bundle;
import android.os.Environment;
import android.os.Handler;
import android.os.Message;
import android.text.Editable;
import android.text.TextWatcher;
import android.util.Base64;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.AdapterView;
import android.widget.ArrayAdapter;
import android.widget.BaseAdapter;
import android.widget.Button;
import android.widget.CompoundButton;
import android.widget.EditText;
import android.widget.GridLayout;
import android.widget.GridView;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.RadioButton;
import android.widget.RadioGroup;
import android.widget.Spinner;
import android.widget.TextView;

import com.bumptech.glide.Glide;
import com.example.administrator.yanfoxconn.R;
import com.example.administrator.yanfoxconn.bean.EmpMessage;
import com.example.administrator.yanfoxconn.bean.FileName;
import com.example.administrator.yanfoxconn.bean.KHInfo;
import com.example.administrator.yanfoxconn.bean.SelectModel;
import com.example.administrator.yanfoxconn.constant.Constants;
import com.example.administrator.yanfoxconn.constant.FoxContext;
import com.example.administrator.yanfoxconn.constant.ImageCaptureManager;
import com.example.administrator.yanfoxconn.intent.PhotoPickerIntent;
import com.example.administrator.yanfoxconn.intent.PhotoPreviewIntent;
import com.example.administrator.yanfoxconn.utils.BaseActivity;
import com.example.administrator.yanfoxconn.utils.FileUtil;
import com.example.administrator.yanfoxconn.utils.HttpConnectionUtil;
import com.example.administrator.yanfoxconn.utils.HttpUtils;
import com.example.administrator.yanfoxconn.utils.ImageZipUtils;
import com.example.administrator.yanfoxconn.utils.StringUtils;
import com.example.administrator.yanfoxconn.utils.ToastUtils;
import com.example.administrator.yanfoxconn.widget.TouchImageView;
import com.google.gson.Gson;
import com.google.gson.JsonArray;
import com.google.gson.JsonElement;
import com.google.gson.JsonObject;
import com.google.gson.JsonParser;

import org.json.JSONArray;

import java.io.File;
import java.io.Serializable;
import java.io.UnsupportedEncodingException;
import java.util.ArrayList;
import java.util.List;

import androidx.core.content.ContextCompat;
import butterknife.BindView;
import butterknife.ButterKnife;

/**
 * 用途：共用
 *        人資-訪談記錄 人員新增
 *                 及 人員詳情
 *
 * Created by Song on 2021/9/14.
 */
public class KHPeopleAddAndDetailActivity extends BaseActivity implements View.OnClickListener {
    private final int MESSAGE_SET_PROBLEM = 1111;//問題类型
    private final int MESSAGE_SET_DEP = 2222;//責任單位
    private final int MESSAGE_SET_TIME = 3333;//處理時效
    private final int MESSAGE_SET_LIST = 4444;//宿舍

    @BindView(R.id.tv_title)
    TextView tvTitle;//標題
    @BindView(R.id.btn_title_left)
    Button btnBack;//返回
    @BindView(R.id.btn_title_right)
    Button btnAdd;//提交

    @BindView(R.id.et_id)
    EditText etId;//受訪人
    @BindView(R.id.tv_id)
    TextView tvId;//受訪人
    @BindView(R.id.tv_name)
    TextView tvName;//受訪人 姓名
    @BindView(R.id.tv_dep)
    TextView tvDep;//受訪人 部門
    @BindView(R.id.tv_work_name)
    TextView tvWorkName;//受訪人工站或宿舍
    @BindView(R.id.et_work_room)
    EditText etWorkRoom;//受訪人
    @BindView(R.id.tv_work_room)
    TextView tvWorkRoom;//受訪人
    @BindView(R.id.btn_check)
    Button btnCheck;
    @BindView(R.id.rg_open)
    RadioGroup rgOpen;//是否公開
    @BindView(R.id.rb_open_y)
    RadioButton rbOpenY;//是否公開
    @BindView(R.id.rb_open_n)
    RadioButton rbOpenN;//是否公開
    @BindView(R.id.tv_open)
    TextView tvOpen;//是否公開
    @BindView(R.id.sp_type)
    Spinner spType;//問題分類
    @BindView(R.id.tv_type)
    TextView tvType;//問題分類
    @BindView(R.id.et_desp)
    EditText etDesp;//具體描述
    @BindView(R.id.tv_desp)
    TextView tvDesp;//具體描述
    @BindView(R.id.sp_to_dep)
    Spinner spToDep;//責任單位
    @BindView(R.id.tv_to_dep)
    TextView tvToDep;//責任單位
    @BindView(R.id.sp_time)
    Spinner spTime;//處理時效
    @BindView(R.id.tv_time)
    TextView tvTime;//處理時效

    private List<EmpMessage> empMessagesList;
    @BindView(R.id.ll_photo)
    LinearLayout llPhoto;
    @BindView(R.id.iv_empty1)
    ImageView ivEmptyOne;//空白图片占位
    @BindView(R.id.gv_photo1)
    GridView gridViewOne;//图片显示区域
    @BindView(R.id.ll_get_image)
    GridLayout getImage;//已有圖片顯示

    private static final int REQUEST_CAMERA_CODE_ONE = 111;
    private static final int REQUEST_PREVIEW_CODE_ONE = 221;
    private ArrayList<String> imagePathsOne = null;//圖片未壓縮地址
    private ArrayList<String> imgZipPathsOne = new ArrayList<String>();//圖片壓縮后地址
    private ImageCaptureManager captureManager; // 相机拍照处理类
    private GridAdapter gridAdapterOne;

    private KHInfo peopleInfo;
    private List<KHInfo> typeInfo,toDepInfo,timeInfo;//問題类型，責任單位，處理時效
    private String type,toDep,time,open="是",id,workFlag;
    private KHPeopleAddAndDetailActivity mContext = this;
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_kh_add_pelple);
        ButterKnife.bind(this);
        btnBack.setOnClickListener(this);
        tvTitle.setText("新增人員");
        btnAdd.setVisibility(View.VISIBLE);
        btnAdd.setOnClickListener(this);
        btnCheck.setOnClickListener(this);
        ivEmptyOne.setOnClickListener(this);
        rbOpenN.setChecked(true);
        rbOpenN.setOnCheckedChangeListener(new CompoundButton.OnCheckedChangeListener() {
            @Override
            public void onCheckedChanged(CompoundButton compoundButton, boolean b) {
                if (b){
                    open="是";
                }else{
                    open="否";
                }
            }
        });
        id=getIntent().getStringExtra("id");
        workFlag=getIntent().getStringExtra("workFlag");
        if (workFlag.equals("產線")){
            tvWorkName.setText("工站");
        }else{
            tvWorkName.setText("宿舍");
        }
        if (id.equals("")){
            peopleInfo= (KHInfo) getIntent().getSerializableExtra("info");
            setText(peopleInfo);
            btnAdd.setText("刪除");
        }else{
            btnAdd.setText("提交");
            getType("i_problem");
        }
        int cols = getResources().getDisplayMetrics().widthPixels / getResources().getDisplayMetrics().densityDpi;
        cols = cols < 4 ? 4 : cols;
        gridViewOne.setNumColumns(cols);

        gridViewOne.setOnItemClickListener(new AdapterView.OnItemClickListener() {
            @Override
            public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
                if (position == imagePathsOne.size()) {
                    PhotoPickerIntent intent = new PhotoPickerIntent(KHPeopleAddAndDetailActivity.this);
                    intent.setSelectModel(SelectModel.MULTI);
                    intent.setShowCarema(true); // 是否显示拍照
                    intent.setMaxTotal(3); // 最多选择照片数量，默认为3
                    intent.setSelectedPaths(imagePathsOne); // 已选中的照片地址， 用于回显选中状态
                    startActivityForResult(intent, REQUEST_CAMERA_CODE_ONE);
                } else {
                    PhotoPreviewIntent intent = new PhotoPreviewIntent(KHPeopleAddAndDetailActivity.this);
                    intent.setCurrentItem(position);
                    intent.setPhotoPaths(imagePathsOne);
                    startActivityForResult(intent, REQUEST_PREVIEW_CODE_ONE);
                }
            }
        });

    }

    private void setText(KHInfo info) {
        tvId.setText(peopleInfo.getI_SNO());
        tvName.setText(peopleInfo.getI_SNAME());
        tvDep.setText(peopleInfo.getI_SDEP());
        tvWorkRoom.setText(peopleInfo.getI_ADDRESS());
        tvOpen.setText(peopleInfo.getI_ISOPEN());
        tvType.setText(peopleInfo.getI_PROBLEMTYPE());
        tvDesp.setText(peopleInfo.getI_DESP());
        tvToDep.setText(peopleInfo.getI_TODEP());
        tvTime.setText(peopleInfo.getI_TIMES());

        tvId.setVisibility(View.VISIBLE);
        tvName.setVisibility(View.VISIBLE);
        tvDep.setVisibility(View.VISIBLE);
        tvWorkRoom.setVisibility(View.VISIBLE);
        tvOpen.setVisibility(View.VISIBLE);
        tvType.setVisibility(View.VISIBLE);
        tvDesp.setVisibility(View.VISIBLE);
        tvToDep.setVisibility(View.VISIBLE);
        tvTime.setVisibility(View.VISIBLE);
        getImage.setVisibility(View.VISIBLE);

        etId.setVisibility(View.GONE);
        etWorkRoom.setVisibility(View.GONE);
        etDesp.setVisibility(View.GONE);
        rgOpen.setVisibility(View.GONE);
        btnCheck.setVisibility(View.GONE);
        spType.setVisibility(View.GONE);
        spToDep.setVisibility(View.GONE);
        spTime.setVisibility(View.GONE);
        llPhoto.setVisibility(View.GONE);

        List<FileName> photos = peopleInfo.getFile();

        for (int i=0;i<photos.size();i++) {

            TouchImageView imageView = new TouchImageView(mContext);
            String imgStr = photos.get(i).getFile();
            Log.e("------imgStr-----", "======" + imgStr);
            byte[] decode = Base64.decode(imgStr, Base64.DEFAULT);
            Bitmap bitmap = BitmapFactory.decodeByteArray(decode, 0, decode.length);
            imageView.setAdjustViewBounds(true);
            imageView.setScaleType(ImageView.ScaleType.CENTER);
            imageView.setImageBitmap(bitmap);
            LinearLayout.LayoutParams layoutParams = new LinearLayout.LayoutParams(200, 200);
            layoutParams.setMargins(10, 10, 10, 10);

            imageView.setLayoutParams(layoutParams);
            int finalI = i;
            imageView.setOnClickListener(new View.OnClickListener() {
                @Override
                public void onClick(View view) {
                    int[] location = new int[2];
                    if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.KITKAT) {
                        Rect frame = new Rect();
                        getWindow().getDecorView().getWindowVisibleDisplayFrame(frame);
                        int statusBarHeight = frame.top;

                        view.getLocationOnScreen(location);
                        location[1] += 0;
                    } else {
                        view.getLocationOnScreen(location);
                    }
                    view.invalidate();
                    int width = view.getWidth();
                    int height = view.getHeight();

                    Intent intent = new Intent(KHPeopleAddAndDetailActivity.this, BigImageActivity.class);
                    Bundle b = new Bundle();
                    b.putString(BigImageActivity.QR_IMAGE_URL, imgStr);
                    intent.putExtras(b);
//                                intent.putExtra(BigImageActivity.PHOTO_SELECT_POSITION,);
                    intent.putExtra(BigImageActivity.PHOTO_SELECT_X_TAG, location[0]);
                    intent.putExtra(BigImageActivity.PHOTO_SELECT_Y_TAG, location[1]);
                    intent.putExtra(BigImageActivity.PHOTO_SELECT_W_TAG, width);
                    intent.putExtra(BigImageActivity.PHOTO_SELECT_H_TAG, height);
                    startActivity(intent);
                    overridePendingTransition(0, 0);
                }
            });
            getImage.addView(imageView);
        }
    }

    @Override
    public void onClick(View view) {
        switch (view.getId()){
            case R.id.btn_title_left://返回
                finish();
                break;
            case R.id.btn_title_right://提交
                if (id.equals("")){
                    aboutAlert("確認刪除人員信息？",Constants.MESSAGE_TOAST);

                }else {
                    check();
                }
                break;
            case R.id.iv_empty1:
                PhotoPickerIntent intent = new PhotoPickerIntent(mContext);
                intent.setSelectModel(SelectModel.MULTI);
                intent.setShowCarema(true); // 是否显示拍照
                intent.setMaxTotal(9); // 最多选择照片数量，默认为3
                intent.setSelectedPaths(imagePathsOne); // 已选中的照片地址， 用于回显选中状态

                startActivityForResult(intent, REQUEST_CAMERA_CODE_ONE);
                break;

            case R.id.btn_check:
                getMessageF(etId.getText().toString());
                break;
        }
    }
    //基本信息下拉   傳值：flag type
    private void getType(String flag){
        new Thread() {
            @Override
            public void run() {
                String url2 = Constants.HTTP_BASIC_INFO + "?flag=" + flag;

                Log.e("---------", "url2==fff===" + url2);
                //把网络访问的代码放在这里
                String result = HttpUtils.queryStringForPost(url2);
                dismissDialog();
                Gson gson = new Gson();
                if (result != null) {
                    Log.e("---------", "result==fff===" + result);
                    JsonObject jsonObject = new JsonParser().parse(result).getAsJsonObject();
                    String errCode = jsonObject.get("errCode").getAsString();
                    if (errCode.equals("200")) {
                        JsonArray array = jsonObject.get("data").getAsJsonArray();
                        typeInfo = new ArrayList<KHInfo>();

                        for (JsonElement type : array) {
                            KHInfo humi = gson.fromJson(type, KHInfo.class);
                            typeInfo.add(humi);
                        }
                        Message message = new Message();
                        message.what = MESSAGE_SET_PROBLEM;
                        message.obj = jsonObject.get("errMessage").getAsString();
                        mHandler.sendMessage(message);
                    }
                } else {
                    Message message = new Message();
                    message.what = Constants.MESSAGE_NETMISTAKE;
                    mHandler.sendMessage(message);
                    finish();
                }
            }
        }.start();
    }
    private void setType(){
        List<String> typeName=new ArrayList<>();
        for (int i = 0;i<typeInfo.size();i++){
            typeName.add(typeInfo.get(i).getNAME());
        }
        //下拉列表選擇
        spType.setAdapter(new ArrayAdapter<String>(this, android.R.layout.simple_list_item_1, typeName));
        spType.setOnItemSelectedListener(new AdapterView.OnItemSelectedListener() {
            @Override
            public void onItemSelected(AdapterView<?> parent, View view, int position, long id) {
                type=typeName.get(position);
            }
            @Override
            public void onNothingSelected(AdapterView<?> parent) {
            }
        });
    }

    //基本信息下拉：責任單位
    private void getToDep(String flag){
        new Thread() {
            @Override
            public void run() {
                String url2 = Constants.HTTP_BASIC_INFO + "?flag=" + flag;

                Log.e("---------", "url2==fff===" + url2);
                //把网络访问的代码放在这里
                String result = HttpUtils.queryStringForPost(url2);
                dismissDialog();
                Gson gson = new Gson();
                if (result != null) {
                    Log.e("---------", "result==fff===" + result);
                    JsonObject jsonObject = new JsonParser().parse(result).getAsJsonObject();
                    String errCode = jsonObject.get("errCode").getAsString();
                    if (errCode.equals("200")) {
                        JsonArray array = jsonObject.get("data").getAsJsonArray();
                        toDepInfo = new ArrayList<KHInfo>();

                        for (JsonElement type : array) {
                            KHInfo humi = gson.fromJson(type, KHInfo.class);
                            toDepInfo.add(humi);
                        }
                        Message message = new Message();
                        message.what = MESSAGE_SET_DEP;
                        message.obj = jsonObject.get("errMessage").getAsString();
                        mHandler.sendMessage(message);
                    }
                } else {
                    Message message = new Message();
                    message.what = Constants.MESSAGE_NETMISTAKE;
                    mHandler.sendMessage(message);
                    finish();
                }
            }
        }.start();
    }
    private void setToDep(){
        List<String> depName=new ArrayList<>();
        for (int i = 0;i<toDepInfo.size();i++){
            depName.add(toDepInfo.get(i).getDEPNAME()+"-"+toDepInfo.get(i).getEMPNAME());
        }
        //下拉列表選擇
        spToDep.setAdapter(new ArrayAdapter<String>(this, android.R.layout.simple_list_item_1, depName));
        spToDep.setOnItemSelectedListener(new AdapterView.OnItemSelectedListener() {
            @Override
            public void onItemSelected(AdapterView<?> parent, View view, int position, long id) {
                toDep=toDepInfo.get(position).getDEPNAME();
            }
            @Override
            public void onNothingSelected(AdapterView<?> parent) {
            }
        });
    }

    //基本信息下拉:處理時效   傳值：i_time
    private void getTime(String flag){
        new Thread() {
            @Override
            public void run() {

                String url2 =  Constants.HTTP_BASIC_INFO + "?flag=" + flag;


                Log.e("---------", "url2==fff===" + url2);
                //把网络访问的代码放在这里
                String result = HttpUtils.queryStringForPost(url2);
                dismissDialog();
                Gson gson = new Gson();
                if (result != null) {
                    Log.e("---------", "result==fff===" + result);
                    JsonObject jsonObject = new JsonParser().parse(result).getAsJsonObject();
                    String errCode = jsonObject.get("errCode").getAsString();
                    if (errCode.equals("200")) {
                        JsonArray array = jsonObject.get("data").getAsJsonArray();
                        timeInfo = new ArrayList<KHInfo>();

                        for (JsonElement type : array) {
                            KHInfo humi = gson.fromJson(type, KHInfo.class);
                            timeInfo.add(humi);
                        }
                        Message message = new Message();
                        message.what = MESSAGE_SET_TIME;
                        message.obj = jsonObject.get("errMessage").getAsString();
                        mHandler.sendMessage(message);
                    }
                } else {
                    Message message = new Message();
                    message.what = Constants.MESSAGE_NETMISTAKE;
                    mHandler.sendMessage(message);
                    finish();
                }
            }
        }.start();
    }
    private void setTime(){
        List<String> timeName=new ArrayList<>();
        for (int i = 0;i<timeInfo.size();i++){
            timeName.add(timeInfo.get(i).getNAME());
        }
        //下拉列表選擇
        spTime.setAdapter(new ArrayAdapter<String>(this, android.R.layout.simple_list_item_1, timeName));
        spTime.setOnItemSelectedListener(new AdapterView.OnItemSelectedListener() {
            @Override
            public void onItemSelected(AdapterView<?> parent, View view, int position, long id) {
                time=timeName.get(position);
            }
            @Override
            public void onNothingSelected(AdapterView<?> parent) {
            }
        });
    }

    //獲取人员信息F
    private void getMessageF(String id){
        showDialog();
        final String url = Constants.HTTP_COMMON_FORMS_SERVLET+"?code="+id;

        new Thread() {
            @Override
            public void run() {
                //把网络访问的代码放在这里
                String result = HttpUtils.queryStringForPost(url);

                dismissDialog();
                Log.e("---------", "==fff===" + url);
                Gson gson = new Gson();
                if (result != null) {
                    Log.e("---------", "result==fff===" + result);

                    JsonObject jsonObject = new JsonParser().parse(result).getAsJsonObject();
                    String errCode = jsonObject.get("errCode").getAsString();
                    if (errCode.equals("200")) {
                        JsonArray array = jsonObject.get("data").getAsJsonArray();
                        empMessagesList = new ArrayList<EmpMessage>();

                        for (JsonElement type : array) {
                            EmpMessage humi = gson.fromJson(type, EmpMessage.class);
                            empMessagesList.add(humi);
                        }

                        Message message = new Message();
                        message.what = Constants.MESSAGE_SET_TEXT;
                        message.obj = jsonObject.get("errMessage").getAsString();
                        mHandler.sendMessage(message);

                    } else{
                        Message message = new Message();
                        message.what = Constants.MESSAGE_TOAST;
                        message.obj = jsonObject.get("errMessage").getAsString();
                        mHandler.sendMessage(message);
                    }
                }
            } }.start();
    }

    //提交前檢查
    private void check(){
        if(FoxContext.getInstance().getLoginId().equals("")){
            ToastUtils.showLong(mContext,"登錄超時,請退出重新登錄!");
            return;
        }
        if (etId.getText().toString().equals("")||tvName.getText().toString().equals("")||etWorkRoom.getText().toString().equals("")){
            ToastUtils.showShort(mContext,"請輸入正確人員信息！");
            return;
        }
        if (etDesp.getText().toString().equals("")){
            ToastUtils.showShort(mContext,"請輸入具體描述！");
            return;
        }

        if (imagePathsOne==null) {
            ToastUtils.showShort(this, "請上傳服務照片");
            return;
        }
        if (imagePathsOne.get(0).toString().equals(imagePathsOne.get(1).toString())) {
            ToastUtils.showShort(this, "tupianyiyang");
            return;
        }
        upMsessage();
    }
    //提交信息
    private void upMsessage() {

        final String url = Constants.HTTP_BODY_ADD; //此處寫上自己的URL

        JsonObject object = new JsonObject();

        JsonArray photoArray1 = new JsonArray();

        if (imagePathsOne != null) {
            for (int i = 0; i < imagePathsOne.size(); i++) {
                File pictureFile = new File(imagePathsOne.get(i)); //通過路徑獲取檔
                final String pic_path = imagePathsOne.get(i);
                String sign_dir = Environment.getExternalStorageDirectory() + File.separator + "YanFoxconn" + File.separator + "Photos";
                String _path =  sign_dir + File.separator  + System.currentTimeMillis() +i+ ".jpg";
                final String compressImage = ImageZipUtils.compressImage(pic_path, _path, 60);
                String picBase64Code = ImageZipUtils.imageToBase64(compressImage);
                JsonObject jsonObject1 = new JsonObject();
                jsonObject1.addProperty("file", picBase64Code);
                photoArray1.add(jsonObject1);
            }
            object.add("photo", photoArray1);
        }

        object.addProperty("i_id",id);
        object.addProperty("i_sno",etId.getText().toString());
        object.addProperty("i_sname",tvName.getText().toString());
        object.addProperty("i_sdep",tvDep.getText().toString());
        object.addProperty("i_address",etWorkRoom.getText().toString());
        object.addProperty("i_isopen",open);
        object.addProperty("i_problemtype",type);
        object.addProperty("i_desp", etDesp.getText().toString());
        object.addProperty("i_todep",toDep);
        object.addProperty("i_times",time);

        Log.e("----object----",  object.toString());

        //開啟一個新執行緒，向伺服器上傳資料
        new Thread() {
            public void run() {
                //把网络访问的代码放在这里
                try {
                    showDialog();
                    Log.e("-----url----",  url);
                    String result = HttpConnectionUtil.doPostJsonObject(url, object);
                    if (result != null) {
                        dismissDialog();
                        Log.e("----result-----",  result);
                        JsonObject jsonObject = new JsonParser().parse(result).getAsJsonObject();
                        String errCode = jsonObject.get("errCode").getAsString();
                        if (errCode.equals("200")) {
                            Message message = new Message();
                            message.what = Constants.MESSAGE_ALERT;
                            message.obj = jsonObject.get("errMessage").getAsString();
                            mHandler.sendMessage(message);

                        } else{
                            Message message = new Message();
                            message.what = Constants.MESSAGE_ALERT;
                            message.obj = jsonObject.get("errMessage").getAsString();
                            mHandler.sendMessage(message);
                        }
                    }else{
                        Message message = new Message();
                        message.what = Constants.MESSAGE_NETMISTAKE;
                        mHandler.sendMessage(message);
                        finish();
                    }

                } catch (Exception e) {
                    e.printStackTrace();
                }finally {
                    FileUtil.deletePhotos(mContext);
                }
            }
        }.start();
    }

    private int num=0;
    Handler mHandler = new Handler() {
        public void handleMessage(Message msg) {
            switch (msg.what) {

                case Constants.MESSAGE_TOAST://Toast彈出
                    ToastUtils.showLong(mContext, msg.obj.toString());
//                    finish();
                    break;
                case Constants.MESSAGE_SET_TEXT://text賦值
//                    aboutAlert(msg.obj.toString(),MESSAGE_SET_TEXT);
                        Log.e("---------",num+"==num");
                        tvName.setText(empMessagesList.get(0).getCHINESENAME());
                        tvDep.setText(empMessagesList.get(0).getORGNAME());
                    if (!workFlag.equals("產線")){
                        getRoom(etId.getText().toString());
                    }
                    break;
                case Constants.MESSAGE_UP://提交響應
//                    worningAlert(msg.obj.toString(),Constants.MESSAGE_TOAST);
//                    ToastUtils.showLong(CrossScanActivity.this, msg.obj.toString());
                    break;
                case Constants.MESSAGE_ALERT://提交響應
//                    worningAlert(msg.obj.toString(),Constants.MESSAGE_TOAST);
                    ToastUtils.showLong(mContext, msg.obj.toString());
                    finish();
                    break;
                case MESSAGE_SET_PROBLEM:
                    setType();
                    getToDep("i_dep");
                    break;
                case MESSAGE_SET_DEP:
                    setToDep();
                    getTime("i_time");
                    break;
                case MESSAGE_SET_TIME:
                    setTime();
                    break;
                case Constants.MESSAGE_DELETE_SUCCESS:
                finish();
                    break;
                case MESSAGE_SET_LIST://設置信息
                    JsonObject mes = (JsonObject) msg.obj;
                    etWorkRoom.setText(mes.get("REGULAREMP_BEDID").getAsString());
                    break;

                case Constants.MESSAGE_NETMISTAKE://Toast
                    ToastUtils.showLong(KHPeopleAddAndDetailActivity.this,R.string.net_mistake);
                    break;
            }
            super.handleMessage(msg);
        }
    };

    /**
     * 獲取員工住宿信息
     * @param id
     */
    private void getRoom(String id) {

            showDialog();
            final String url = Constants.HTTP_STORE_OERSION_INFO + "?userid=" + id;

            new Thread() {
                @Override
                public void run() {
                    //把网络访问的代码放在这里
                    String result = HttpUtils.queryStringForGet(url);
                    Log.e("---------", "result==fff===" + result);
                    dismissDialog();
                    Log.e("---------", "==fff===" + url);
                    Gson gson = new Gson();
                    if (result != null) {
                        JsonObject jsonObject = new JsonParser().parse(result).getAsJsonObject();
                        String errCode = jsonObject.get("errCode").getAsString();
                        if (errCode.equals("200")) {
                            Log.e("--fff---------", "result==" + result);
                            JsonObject array = jsonObject.get("data").getAsJsonObject();
//                        igMessageList = new ArrayList<IGMessage>();
//
//                        for (JsonElement type : array) {
//                            IGMessage humi = gson.fromJson(type, IGMessage.class);
//                            igMessageList.add(humi);
//                        }


                            Message message = new Message();
                            message.what = MESSAGE_SET_LIST;
                            message.obj = array;
                            mHandler.sendMessage(message);

                        } else {
                            Log.e("-----------", "result==" + result);
                            Message message = new Message();
                            message.what = Constants.MESSAGE_TOAST;
                            message.obj = jsonObject.get("errMessage").getAsString();
                            mHandler.sendMessage(message);
                        }
                    }else{
                        Message message = new Message();
                        message.what = Constants.MESSAGE_NETMISTAKE;
                        mHandler.sendMessage(message);
                    }
                }
            }.start();
    }

    //照片上傳 返回
    @Override
    protected void onActivityResult(int requestCode, int resultCode, Intent data) {
        super.onActivityResult(requestCode, resultCode, data);
        if (resultCode == RESULT_OK) {

            switch (requestCode) {
                // 选择照片
                case REQUEST_CAMERA_CODE_ONE:
                    loadAdpater(data.getStringArrayListExtra(PhotoPickerActivity.EXTRA_RESULT), requestCode);
                    break;
                // 预览
                case REQUEST_PREVIEW_CODE_ONE:
                    loadAdpater(data.getStringArrayListExtra(PhotoPreviewActivity.EXTRA_RESULT), requestCode);
                    break;
                // 调用相机拍照
                case ImageCaptureManager.REQUEST_TAKE_PHOTO:
                    if (captureManager.getCurrentPhotoPath() != null) {
                        captureManager.galleryAddPic();

                        ArrayList<String> paths = new ArrayList<>();
                        paths.add(captureManager.getCurrentPhotoPath());
                        loadAdpater(paths, requestCode);
                    }
                    break;
            }
        }
    }

    private void loadAdpater(ArrayList<String> paths, int code) {
        switch (code) {
            case REQUEST_CAMERA_CODE_ONE:
                loadOne(paths);
                break;
            case REQUEST_PREVIEW_CODE_ONE:
                loadOne(paths);
                break;
        }
    }

    private void loadOne(ArrayList<String> paths) {
        if (imagePathsOne == null) {
            imagePathsOne = new ArrayList<>();
        }
        imagePathsOne.clear();
        imagePathsOne.addAll(paths);

        if (paths.size() > 0) {
            ivEmptyOne.setVisibility(View.GONE);
        } else {
            ivEmptyOne.setVisibility(View.VISIBLE);
        }

        try {
            JSONArray obj = new JSONArray(imagePathsOne);
            Log.e("--", obj.toString());
        } catch (Exception e) {
            e.printStackTrace();
        }

        if (gridAdapterOne == null) {
            gridAdapterOne = new GridAdapter(imagePathsOne);
            gridViewOne.setAdapter(gridAdapterOne);
            Log.e("----------------", "ddd==" + imagePathsOne.size());
        } else {
            gridAdapterOne.notifyDataSetChanged();
        }
    }

    private class GridAdapter extends BaseAdapter {
        private ArrayList<String> listUrls;

        public GridAdapter(ArrayList<String> listUrls) {
            this.listUrls = listUrls;
        }

        @Override
        public int getCount() {
            if (listUrls.size() == 9) {
                return 9;
            } else {
                return listUrls.size() + 1;
            }

        }

        @Override
        public String getItem(int position) {
            return listUrls.get(position);
        }

        @Override
        public long getItemId(int position) {
            return position;
        }

        @Override
        public View getView(int position, View convertView, ViewGroup parent) {
            ImageView imageView;
            if (convertView == null) {
                convertView = getLayoutInflater().inflate(R.layout.item_image, null);
                imageView = (ImageView) convertView.findViewById(R.id.imageView);
                convertView.setTag(imageView);
                // 重置ImageView宽高
//                LinearLayout.LayoutParams params = new LinearLayout.LayoutParams(columnWidth, columnWidth);
//                imageView.setLayoutParams(params);
            } else {
                imageView = (ImageView) convertView.getTag();
            }

            if (position == listUrls.size()) {
                imageView.setImageBitmap(BitmapFactory.decodeResource(getResources(), R.mipmap.icon_addpic_unfocused));
                if (position == 9) {
                    imageView.setVisibility(View.GONE);
                }
            } else {
                Glide.with(mContext)
                        .load(new File(getItem(position)))
                        .placeholder(R.mipmap.default_error)
                        .error(R.mipmap.default_error)
                        .centerCrop()
                        .crossFade()
                        .into(imageView);
            }
            return convertView;
        }
    }

    /**
     * 刪除單頭
     * @param i_id 單頭
     * @param i_item 人員
     * @param flag 標誌
     */
    private void deleteBody(String i_id, String i_item, String flag) {

        final String url = Constants.HTTP_DELETE_BY_FLAG+"?i_id="+i_id+
                "&i_item="+i_item+"&flag="+flag; //此處寫上自己的URL

        //開啟一個新執行緒，向伺服器上傳資料
        new Thread() {
            public void run() {
                //把网络访问的代码放在这里
                try {
                    showDialog();
                    String result = HttpUtils.queryStringForPost(url);

                    if (result != null) {
                        dismissDialog();
                        Log.e("----result-----",  result);
                        JsonObject jsonObject = new JsonParser().parse(result).getAsJsonObject();
                        String errCode = jsonObject.get("errCode").getAsString();
                        if (errCode.equals("200")) {

                            Message message = new Message();
                            message.what = Constants.MESSAGE_DELETE_SUCCESS;
                            message.obj = jsonObject.get("errMessage").getAsString();
                            mHandler.sendMessage(message);
                        }
                    }else{
                        Message message = new Message();
                        message.what = Constants.MESSAGE_NETMISTAKE;
                        mHandler.sendMessage(message);
                    }

                } catch (Exception e) {
                    e.printStackTrace();
                }
            }
        }.start();
    }


    private void aboutAlert(String msg, final int type) {
        AlertDialog.Builder builder = new AlertDialog.Builder(this);
        builder.setTitle("確認信息")
                .setMessage(msg)
                .setCancelable(false)
                .setPositiveButton("確認", new DialogInterface.OnClickListener() {
                    @Override
                    public void onClick(DialogInterface dialog, int id) {
                        // TODO Auto-generated method stub
                        if (type==Constants.MESSAGE_TOAST){
                            deleteBody(peopleInfo.getI_ID(),peopleInfo.getI_ITEM(),"body");
                        }
                    }
                })
                .setNegativeButton("取消", new DialogInterface.OnClickListener() {
                    @Override
                    public void onClick(DialogInterface dialog, int id) {
                        // TODO Auto-generated method stub
//                        if (type==MESSAGE_TOAST){
//                            finish();
//                        }else if(type==MESSAGE_UP){
//                            check();
//                        }
                    }
                });
        AlertDialog alert = builder.create();
        alert.show();
    }

}
